//
//  JianFaViewController.m
//  HeadYang
//
//  Created by sunmingming on 15/7/12.
//  Copyright (c) 2015年 xiaoluoli. All rights reserved.
//

#import "JianFaViewController.h"
#import "JSDropDownMenu.h"
#import "SpCityItem.h"
#import "StoreDetailViewController.h"
#import "BarberDetailViewController.h"
#import "UIImageView+AFNetworking.h"
#import "PullingRefreshTableView.h"

@interface JianFaViewController ()<JSDropDownMenuDelegate,UITableViewDataSource,UITableViewDelegate,PullingRefreshTableViewDelegate>{
    JSDropDownMenu *menu;
}
@property(nonatomic,weak) IBOutlet PullingRefreshTableView *listView;
@property(assign,nonatomic) BOOL refreshing;
@property(assign,nonatomic) NSInteger page;

@property(nonatomic,assign) NSInteger isStore;
@property(nonatomic,assign) NSInteger sortType;

typedef enum
{
    ESoapGetBarbers = 0,
    ESoapGetStores,
}EHTTPWays;
@property(nonatomic,assign) EHTTPWays myHTTPWay;

@property(nonatomic,strong) NSMutableArray *barberArray;
@property(nonatomic,strong) NSMutableArray *storeArray;

@end

@implementation JianFaViewController

@synthesize listView;
@synthesize barberArray = _barberArray;
@synthesize storeArray = _storeArray;
@synthesize refreshing = _refreshing;
@synthesize page = _page;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        switch (APPALL.myType) {
            case hairJianFa:
                self.title = @"剪发";
                break;
            case hairTangFa:
                self.title = @"烫发";
                break;
            case hairRanFa:
                self.title = @"染发";
                break;
            case hairHuli:
                self.title = @"护理";
                break;
            default:
                break;
        }
        self.isStore = 0;
        self.sortType = 0;
        self.navigationItem.leftBarButtonItem =
        [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_white"]
                                         style:UIBarButtonItemStyleDone
                                        target:self
                                        action:@selector(backPressed:)];
        menu = [[JSDropDownMenu alloc] initWithOrigin:CGPointMake(0,0) andHeight:44];
        menu.delegate = self;
        [self.view addSubview:menu];
        
        self.barberArray = [NSMutableArray array];
        self.storeArray = [NSMutableArray array];
    }
    return self;
}

-(void)backPressed:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _page = 0;
    _refreshing = YES;
    self.listView.pullingDelegate = self;
    [self.listView awakeWhenXIB:self.listView.frame];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self AskSoapForHTTPWay:ESoapGetBarbers];
}

- (void)menu:(JSDropDownMenu *)menu didSelectRowAtIndexPath:(JSIndexPath *)indexPath {
    NSLog(@"yeah??");
    switch (indexPath.column) {
        case 0:{
            self.isStore = indexPath.row;
            _page = 0;
            _refreshing = YES;
            if(self.isStore){
                [self AskSoapForHTTPWay:ESoapGetStores];
            }else {
                [self AskSoapForHTTPWay:ESoapGetBarbers];
            }
        }
            break;
        case 1:{
            self.sortType = indexPath.row;
            _page = 0;
            _refreshing = YES;
            if(self.isStore){
                [self AskSoapForHTTPWay:ESoapGetStores];
            }else {
                [self AskSoapForHTTPWay:ESoapGetBarbers];
            }
        }
            break;
        default:
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(self.isStore)
        return self.storeArray.count;
    else
        return self.barberArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100.0f;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *inde;
    if (self.isStore) {
        inde = @"StoreID";
        cell = [tableView dequeueReusableCellWithIdentifier:inde];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"StoreCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
        UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
        UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
        UILabel *lab4 = (UILabel*)[cell viewWithTag:4];
        UILabel *lab5 = (UILabel*)[cell viewWithTag:5];
        UIImageView *headImg = (UIImageView*)[cell viewWithTag:99];
        NSDictionary *cacheItem = [_storeArray objectAtIndex:indexPath.row];
        lab1.text = [tooles replaceNullFromDic:cacheItem withKeyArray:@[@"name"]];
        lab2.text = [NSString stringWithFormat:@"接单%@次",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"orderExperience"]]];
        lab3.text =  [NSString stringWithFormat:@"<%@km",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"distance"]]];
        lab4.text = [NSString stringWithFormat:@"￥%@",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"averagePrice"]]];
        lab5.text = [tooles replaceNullFromDic:cacheItem withKeyArray:@[@"intro"]];
        NSString *headImage = [[cacheItem objectForKey:@"miniPic"] valueForKey:@"url"];
        if(![headImage isEqual:[NSNull null]]
           && headImage
           && headImage.length){
//            [headImg setImageWithURL:[NSURL URLWithString:headImage]
//                  placeholderImage:[UIImage imageNamed:@"default_photo.png"]];
        }
    }else{
        inde= @"BarberID";
        cell = [tableView dequeueReusableCellWithIdentifier:inde];
        if (cell == nil) {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"BarberCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        UILabel *lab1 = (UILabel*)[cell viewWithTag:1];
        UILabel *lab2 = (UILabel*)[cell viewWithTag:2];
        UILabel *lab3 = (UILabel*)[cell viewWithTag:3];
        UILabel *lab4 = (UILabel*)[cell viewWithTag:4];
        UIImageView *img1 = (UIImageView*)[cell viewWithTag:11];
        UIImageView *img2 = (UIImageView*)[cell viewWithTag:12];
        UIImageView *img3 = (UIImageView*)[cell viewWithTag:13];
        UIImageView *img4 = (UIImageView*)[cell viewWithTag:14];
        UIImageView *img5 = (UIImageView*)[cell viewWithTag:15];
        UIImageView *headImg = (UIImageView*)[cell viewWithTag:99];
        NSDictionary *cacheItem = [_barberArray objectAtIndex:indexPath.row];
        lab1.text = [tooles replaceNullFromDic:cacheItem withKeyArray:@[@"name"]];
        lab2.text = [NSString stringWithFormat:@"接单%@次",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"orderExperience"]]];
        lab3.text =  [NSString stringWithFormat:@"<%@km",[tooles replaceNullFromDic:cacheItem withKeyArray:@[@"distance"]]];
        NSString *headImage = [cacheItem valueForKey:@"headImage"];
        if(![headImage isEqual:[NSNull null]]
           && headImage
           && headImage.length){
            [headImg setImageWithURL:[NSURL URLWithString:headImage]
                    placeholderImage:[UIImage imageNamed:@"default_photo.png"]];
        }
        NSInteger score = [[cacheItem valueForKey:@"score"] integerValue];
        img1.hidden = YES;
        img2.hidden = YES;
        img3.hidden = YES;
        img4.hidden = YES;
        img5.hidden = YES;
        if(score > 0){img1.hidden = NO;}
        if(score > 20){img2.hidden = NO;}
        if(score > 40){img3.hidden = NO;}
        if(score > 60){img4.hidden = NO;}
        if(score > 80){img5.hidden = NO;}
        lab4.text = [NSString stringWithFormat:@"￥%@",[cacheItem valueForKey:@"averagePrice"]];
    }
//    UIImageView *iv = (UIImageView*)[cell viewWithTag:99];
//    iv.layer.masksToBounds =YES;
//    iv.layer.cornerRadius = iv.frame.size.width/2;
//    [iv sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://lihui.ddns.net:7373/HCB/api/user/head?token=%@",APPALL.myUserItem.token]]
//          placeholderImage:[UIImage imageNamed:@"head.png"]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isStore) {
        NSDictionary *cacheItem = [_storeArray objectAtIndex:indexPath.row];
        StoreDetailViewController *vc = [StoreDetailViewController new];
        vc.storeDic = cacheItem;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        NSDictionary *cacheItem = [_barberArray objectAtIndex:indexPath.row];
        BarberDetailViewController *vc = [BarberDetailViewController new];
        vc.barberDic = cacheItem;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)AskSoapForHTTPWay:(EHTTPWays)aHTTPWay
{
    self.myHTTPWay = aHTTPWay;
    NSString *sortStr;
    switch (self.sortType) {
        case 0:
            sortStr = @"distance";
            break;
        case 1:
            sortStr = @"score";
            break;
        case 2:
            sortStr = @"avpm";
            break;
        case 3:
            sortStr = @"avpx";
            break;
        default:
            sortStr = @"";
            break;
    }
    switch (self.myHTTPWay) {
        case ESoapGetBarbers:
        {
            NSDictionary *para =
            @{@"max":@"10",
              @"offset":[NSString stringWithFormat:@"%i",_page * 10],
              @"sort":sortStr,
              @"lat":[NSString stringWithFormat:@"%f",APPALL.location.coordinate.latitude],
              @"lng":[NSString stringWithFormat:@"%f",APPALL.location.coordinate.longitude],
              @"city":@"0",
              @"domain":@"0",
              @"avpm":@"0",
              @"avpx":@"10000",
              @"credit":@"0",
              @"score":@"0",
              @"token":APPALL.myUserItem.token};
            [SVProgressHUD showWithStatus:@"loading..."];
            [AVCloud callFunctionInBackground:@"barber_find" withParameters:para block:^(id object, NSError *error) {
                // 执行结果
                [self.listView tableViewDidFinishedLoading];
                if (!error && object) {
                    NSLog(@"avget:%@",object);
                    NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
                    switch ([[aSucData valueForKey:@"success"] intValue]) {
                        case 0:
                        {
                            [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        }
                            break;
                        case 1:
                        {
                            NSLog(@"yeah1....");
                            if(_refreshing){
                                [_barberArray removeAllObjects];
                            }
                            NSArray *cityArray = [aSucData objectForKey:@"barber"];
                            for (NSDictionary *dic in cityArray) {
                                [_barberArray addObject:dic];
                            }
                            [listView reloadData];
                        }
                            break;
                        default:
                            break;
                    }
                    [SVProgressHUD dismiss];
                } else {
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
                }
            }];
        }
            break;
        case ESoapGetStores:
        {
            NSDictionary *para =
            @{@"max":@"10",
              @"offset":[NSString stringWithFormat:@"%i",_page * 10],
              @"sort":sortStr,
              @"lat":[NSString stringWithFormat:@"%f",APPALL.location.coordinate.latitude],
              @"lng":[NSString stringWithFormat:@"%f",APPALL.location.coordinate.longitude],
              @"city":@"0",
              @"domain":@"0",
              @"avpm":@"0",
              @"avpx":@"10000",
              @"credit":@"0",
              @"score":@"0",
              @"token":APPALL.myUserItem.token};
            [SVProgressHUD showWithStatus:@"loading..."];
            [AVCloud callFunctionInBackground:@"store_find" withParameters:para block:^(id object, NSError *error) {
                // 执行结果
                [self.listView tableViewDidFinishedLoading];
                if (!error && object) {
                    NSLog(@"avget:%@",object);
                    NSDictionary *aSucData = [NSJSONSerialization JSONObjectWithData: [object dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableLeaves error: &error];
                    switch ([[aSucData valueForKey:@"success"] intValue]) {
                        case 0:
                        {
                            [tooles showGlobalAlertWithTitle:@"" andMsg:[aSucData valueForKey:@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
                        }
                            break;
                        case 1:
                        {
                            NSLog(@"yeah2....");
                            if(_refreshing){
                                [_storeArray removeAllObjects];
                            }
                            NSArray *cityArray = [aSucData objectForKey:@"store"];
                            NSLog(@"yeahcount:%i",cityArray.count);
                            for (NSDictionary *dic in cityArray) {
                                [_storeArray addObject:dic];
                            }
                            [listView reloadData];
                        }
                            break;
                        default:
                            break;
                    }
                    [SVProgressHUD dismiss];
                } else {
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", error]];
                }
            }];
        }
            break;
        default:
            break;
    }
}

#pragma mark - PullingRefreshTableViewDelegate
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView{
    self.refreshing = YES;
    self.page = 0;
    if(self.isStore){
        [self AskSoapForHTTPWay:ESoapGetStores];
    }else {
        [self AskSoapForHTTPWay:ESoapGetBarbers];
    }
}

- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView{
    self.refreshing = NO;
    self.page++;
    if(self.isStore){
        [self AskSoapForHTTPWay:ESoapGetStores];
    }else {
        [self AskSoapForHTTPWay:ESoapGetBarbers];
    }
}

#pragma mark - Scroll
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.listView tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [self.listView tableViewDidEndDragging:scrollView];
}

@end